﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System.Management;
using System.Collections;
using System.Net;

namespace WindowsFormsApplication2
{
    class WindowsFun
    {
        #region [Windows系统命令]
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        internal struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;
        }

        [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern IntPtr GetCurrentProcess();

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

        [DllImport("advapi32.dll", SetLastError = true)]
        internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool ExitWindowsEx(int flg, int rea);

        internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
        internal const int TOKEN_QUERY = 0x00000008;
        internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        internal const int EWX_LOGOFF = 0x00000000;
        internal const int EWX_SHUTDOWN = 0x00000001;
        internal const int EWX_REBOOT = 0x00000002;
        internal const int EWX_FORCE = 0x00000004;
        internal const int EWX_POWEROFF = 0x00000008;
        internal const int EWX_FORCEIFHUNG = 0x00000010;

        private static bool DoExitWin(int flg)
        {
            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
            ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            ok = ExitWindowsEx(flg, 0);
            return ok;
        }

        /// <summary>
        /// 注销Windows
        /// </summary>
        public static void Winlogoff()
        {
            DoExitWin(EWX_LOGOFF);
        }

        /// <summary>
        /// 重启Windows
        /// </summary>
        public static void Winreboot()
        {
            DoExitWin(EWX_REBOOT);
        }

        /// <summary>
        /// Windows关机
        /// </summary>
        public static void WinShutdown()//关机
        {
            DoExitWin(EWX_SHUTDOWN);
        }
        #endregion

        #region [系统属性]
        /// <summary>
        /// 获取本机IP地址列表
        /// </summary>
        /// <returns></returns>
        public static string[] GetLocalHostIP()
        {
            IPHostEntry hostinfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ips = hostinfo.AddressList;
            string[] strLocalHostIPs = new string[ips.Length];

            for (int index = 0; index < ips.Length; index++)
            {
                strLocalHostIPs[index] = ips[index].ToString();
            }

            return strLocalHostIPs;
        }

        /// <summary>
        /// 获取硬盘分区列表
        /// </summary>
        /// <returns></returns>
        public static ArrayList GetDiskDriectoryInfo()
        {
            ArrayList alDisk = new ArrayList();
            SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
            try
            {
                foreach (ManagementObject disk in searcher.Get())
                {
                    alDisk.Add(disk["Name"].ToString());//获取驱动器盘符
                }
            }
            catch
            {
                return null;
            }
            return alDisk;
        }

        /// <summary>
        /// 获取主板信息
        /// </summary>
        /// <returns></returns>
        public static ArrayList GetBaseBoardInfo()
        {
            ArrayList alMainBoard = new ArrayList();
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BaseBoard");
                foreach (ManagementObject mo in searcher.Get())
                {
                    alMainBoard.Add(mo["Manufacturer"].ToString());//生产商
                    alMainBoard.Add(mo["Product"].ToString());//型号，如“KT400A-8235”
                    alMainBoard.Add(mo["SerialNumber"].ToString());//序列号
                }
            }
            catch
            {
                return null;
            }
            return alMainBoard;
        }

        /// <summary>
        /// 获取Bios信息
        /// </summary>
        /// <returns></returns>
        public static ArrayList GetBiosInfo()
        {
            ArrayList alBIOS = new ArrayList();
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS");
                foreach (ManagementObject mo in searcher.Get())
                {
                    alBIOS.Add(mo["Manufacturer"].ToString());//制造商，如“Phoenix Technologies, LTD” 
                    alBIOS.Add(mo["SerialNumber"].ToString());//序列号
                }
            }
            catch
            {
                return null;
            }
            return alBIOS;
        }

        /// <summary>
        /// 获取CPU信息
        /// </summary>
        /// <returns></returns>
        public static ArrayList GetProcessorInfo()
        {
            ArrayList alCPU = new ArrayList();
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Processor");
                foreach (ManagementObject mo in searcher.Get())
                {
                    alCPU.Add(mo["L2CacheSize"].ToString());//二级缓存，如“512”
                    alCPU.Add(mo["Manufacturer"].ToString());//制造商，如“AuthenticAMD”
                    alCPU.Add(mo["MaxClockSpeed"].ToString());//主频，如“1824”（1.824G）
                    alCPU.Add(mo["ProcessorId"].ToString());//ID，如“0383F9FF000006A0”
                }
            }
            catch
            {
                return null;
            }
            return alCPU;
        }

        /// <summary>
        /// 获取光驱
        /// </summary>
        /// <returns></returns>
        public static ArrayList SetCDRomState()
        {
            ArrayList alCDRom = new ArrayList();
            try
            {
                SelectQuery query = new SelectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType=3");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                foreach (ManagementBaseObject envVar in searcher.Get())
                {
                    alCDRom.Add(envVar["Name"].ToString());
                }
            }
            catch
            {
                return null;
            }
            return alCDRom;
        }

        /// <summary>
        /// 获取WMI设备信息
        /// </summary>
        /// <returns></returns>
        public static ArrayList GetWMIInfo()
        {
            ArrayList alWMI = new ArrayList();
            String strQuery = "select * from meta_class";
            //2.引用ManagementObjectSearcher
            ManagementObjectSearcher Query = new ManagementObjectSearcher(strQuery);
            //3.擷取各種WMI集合
            ManagementObjectCollection EnumWMI = Query.Get();
            //4.列舉WMI類別
            foreach (ManagementObject searcher in EnumWMI)
            {
                alWMI.Add(searcher.ToString());
            }
            return alWMI;
        }


        #endregion

        #region [根据内容查找文件]
        /// <summary>
        /// 按照内容查找的列外扩展名
        /// </summary>
        private static string[] strArrayExtension = { ".RMVB", ".AVI", ".MPEG", ".MPG", ".DIVX", ".MKV", ".WMV" };
        /// <summary>
        /// Word扩展名
        /// </summary>
        private static string[] strArrayWordExtension = { ".DOC", ".RTF", ".DOCX" };
        /// <summary>
        /// PowerPoint扩展名
        /// </summary>
        private static string[] strArrayPowerPointExtension = { ".PPT", ".PPTX" };

        /// <summary>
        /// 判断文件是否包含指定字符串
        /// </summary>
        /// <param name="strSearchContent">指定字符串</param>
        /// <param name="file">文件</param>
        /// <returns></returns>
        public static bool ChargeFileExsitString(string strSearchContent, FileInfo file)
        {
            bool bReturn = false;
            //排除例外扩展名
            string strExtensionName = System.IO.Path.GetExtension(file.FullName.ToString());
            if (((IList)strArrayExtension).Contains(strExtensionName.ToUpper()))
            {
                return false;
            }
            try
            {
                object oMissing = System.Reflection.Missing.Value;

                if (((IList)strArrayWordExtension).Contains(strExtensionName.ToUpper()))//word文件
                {
                    bReturn = ChargeWordFile(strSearchContent, file);
                }
                else if (((IList)strArrayPowerPointExtension).Contains(strExtensionName.ToUpper()))//PowerPoint文件
                {
                    bReturn = ChargePowerPointFile(strSearchContent, file);
                }
                else
                {
                    //文本文件
                    StreamReader sr = new StreamReader(file.FullName.ToString(), System.Text.Encoding.Default);
                    string strLine;
                    while ((strLine = sr.ReadLine()) != null)
                    {
                        if (strLine.IndexOf(strSearchContent) != -1)
                        {
                            bReturn = true;
                            break;
                        }
                    }
                    sr.Close();
                }
            }
            catch
            {
                bReturn = false;
            }
            return bReturn;
        }

        /// <summary>
        /// 判断Word文件是否包含指定字符串
        /// </summary>
        /// <param name="strSearch"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool ChargeWordFile(string strSearch, FileInfo file)
        {
            bool bWordReturn = false;
            object readOnly = true;
            object missing = System.Reflection.Missing.Value;
            object fileName = file.FullName;
            Word.ApplicationClass wordapp = new Word.ApplicationClass();
            Word.Document doc = wordapp.Documents.Open(ref fileName,
        ref missing, ref readOnly, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
            string text = doc.Content.Text;
            doc.Close(ref missing, ref missing, ref missing);
            wordapp.Quit(ref missing, ref missing, ref missing);

            if (text.IndexOf(strSearch) != -1)
            {
                bWordReturn = true;
            }
            return bWordReturn;
        }

        /// <summary>
        /// 判断PowerPoint文件是否包含指定字符串
        /// </summary>
        /// <param name="strSearch"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool ChargePowerPointFile(string strSearch, FileInfo file)
        {
            bool bPowerPointReturn = false;
            PowerPoint.Application pa = new PowerPoint.ApplicationClass();
            PowerPoint.Presentation pp = pa.Presentations.Open(file.FullName,
                            Microsoft.Office.Core.MsoTriState.msoTrue,
                            Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoFalse);
            string pps = "";

            foreach (PowerPoint.Slide slide in pp.Slides)
            {
                if (!bPowerPointReturn)
                {
                    foreach (PowerPoint.Shape shape in slide.Shapes)
                    {
                        pps += shape.TextFrame.TextRange.Text.ToString();
                        if (pps.IndexOf(strSearch) != -1)
                        {
                            bPowerPointReturn = true;
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
            pp.Close();
            pa.Quit();
            return bPowerPointReturn;
        }

        #endregion
    }
}
